package com.wlper.lib.view;

import java.util.ArrayList;
import java.util.List;

import com.android.nearshop.R;
import com.wlper.lib.sys.Screen;
import com.wlper.lib.uitls.ViewUtils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioGroup;

/**
 * 带有下拉窗口的Tab按钮。为了保证点击下拉窗口以外区域能够收起窗口，需要复写Activity的onTouchEvent方法()，
 * 在该方法中调用hideDropdownWindow()
 * 
 * @Override public void onBackPressed() { if (tabs.isDropdownWindowShowing()) {
 *           tabs.hideDropdownWindow(); }else { super.onBackPressed(); } }
 * 
 * @Override public boolean onTouchEvent(MotionEvent event) {
 *           tabs.hideDropdownWindow(); return super.onTouchEvent(event); }
 * 
 * @Override public boolean dispatchTouchEvent(MotionEvent ev) {
 * 
 *           switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: //
 *           如果隐藏下拉窗口成功的话，就不把Touch事件传递给下层的控件了 if (hideDropWindow()) { return
 *           true; } } return super.dispatchTouchEvent(ev); }
 * 
 * 
 * @author wanliang527
 * @date 2014-06-05
 */

public class ExpandableTab extends LinearLayout implements OnDismissListener {

    private final static double WIN_HEIGHT_SCALE = 0.9;// 下拉窗口的高度与屏幕宽度值的比例。
    private final static int COMPOUND_D_PADDING = 20;

    private final static int TAG_KEY_POS = R.id.wl_tag1;
    private final static int TAG_KEY_DROPWIN = R.id.wl_tag2;

    private final static int TAB_MIN_WIDTH = 10;
    private int paddingLeft = 0, paddingRight = 0, paddingTop = 0,
            paddingBottom = 0; // TabButton的Padding值

    private Context mContext;
    private List<CheckBox> mTabs = new ArrayList<CheckBox>();
    private SparseArray<View> mDropWinContents = new SparseArray<View>();
    private CheckBox checkedButton1; // 记录当前被勾选的Tab按钮，用于Tab按钮的点击监听器中，控制同时只有一个CheckBox是勾选状态
    private CheckBox checkedButton2; // 记录当前被勾选的Tab按钮，用于Tab按钮的Check监听器中

    private PopupWindow mPwindow1;// 占据半个屏幕宽度的下拉窗口
    private PopupWindow mPwindow2;// 占据整个屏幕宽度的下拉窗口

    private Screen mScreen;// 屏幕参数
    /**
     * CheckBox的状态监测事件
     */
    private CompoundButton.OnCheckedChangeListener checkedListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            if (isChecked) {
                checkedButton2 = (CheckBox) buttonView;
                hideDropdownWindow();
                Object window = buttonView.getTag(TAG_KEY_DROPWIN);
                if (window != null && window instanceof PopupWindow) {
                    int pos = (Integer) buttonView.getTag(TAG_KEY_POS);
                    View view = mDropWinContents.get(pos);
                    if (view != null) {
                        showPopup((PopupWindow) window, view, buttonView);
                    }
                }
            } else {
                if (checkedButton2.equals(buttonView)) {
                    checkedButton2 = null;
                    hideDropdownWindow();
                }
            }
        }
    };

    /**
     * 按钮点击事件处理。用来控制几个CheckBox的勾选状态，一次最多只能有一个CheckBox是勾选状态
     */
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v instanceof CheckBox) {
                CheckBox button = (CheckBox) v;
                if (checkedButton1 == null) {
                    checkedButton1 = button;
                } else if (!checkedButton1.equals(button)) {
                    checkedButton1.setChecked(false);
                    checkedButton1 = button;
                }
            }

        }
    };

    public ExpandableTab(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ExpandableTab(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        this.setOrientation(RadioGroup.HORIZONTAL);
        mScreen = Screen.getInstance(context);
        mPwindow1 = new PopupWindow(mContext);
        try {
            mPwindow1 = new PopupWindow((int) (mScreen.getScreenWidth() * 0.5),
                    (int) (mScreen.getScreenWidth() * WIN_HEIGHT_SCALE));
        } catch (NullPointerException e) {
            mPwindow1 = new PopupWindow(new View(mContext),(int) (mScreen.getScreenWidth() * 0.5),
                    (int) (mScreen.getScreenWidth() * WIN_HEIGHT_SCALE));
        }
       
        mPwindow1.setAnimationStyle(R.style.wl_PopupWindowAnimation);
        // mPwindow1.setOutsideTouchable(true);
        OnDismissListener listener = new OnDismissListener() {
            @Override
            public void onDismiss() {
                if (checkedButton1 != null) {
                    checkedButton1.setChecked(false);
                    checkedButton1 = null;
                }

            }
        };
        mPwindow1.setOnDismissListener(listener);
        try {
            mPwindow2 = new PopupWindow((int) (mScreen.getScreenWidth()),
                    (int) (mScreen.getScreenWidth() * WIN_HEIGHT_SCALE));
        } catch (NullPointerException e) {
            mPwindow2 = new PopupWindow(new View(mContext),(int) (mScreen.getScreenWidth()),
                    (int) (mScreen.getScreenWidth() * WIN_HEIGHT_SCALE));
        }
        
        mPwindow2.setAnimationStyle(R.style.wl_PopupWindowAnimation);
        mPwindow2.setOnDismissListener(listener);

    }

    /**
     * 添加Button
     * 
     * @param title
     */
    public void addTabButton(String title) {
        CheckBox button = createTabButton();
        int pos = mTabs.size();
        button.setTag(TAG_KEY_POS, pos);
        // 千万不要随便设置ID，有可能会与其它控件的ID出现重复，造成错误
        // button.setId(mTabs.size());
        button.setOnCheckedChangeListener(checkedListener);
        button.setOnClickListener(clickListener);
        // button.setOnTouchListener(clickListener);
        this.addView(button);
        mTabs.add(button);
        setTitle(pos, title);
        ((LinearLayout.LayoutParams) button.getLayoutParams()).weight = 1;
    }

    /**
     * 添加Button
     * 
     * @param title
     * @param drawableId
     */
    public void addTabButton(String title, int drawableId) {
        addTabButton(title);
        setIcon(mTabs.size() - 1, drawableId);
    }

    private boolean hidePopup(PopupWindow window) {
        if (window != null && window.isShowing()) {
            window.dismiss();
            return true;
        }
        return false;

    }

    private void showPopup(PopupWindow window, View contentView, View anchor) {
        if (window != null && !window.isShowing()) {
            window.setContentView(contentView);
            window.showAsDropDown(anchor, 0, 0);
        }
    }

    /**
     * 创建默认风格的Button
     * 
     * @return
     */
    private CheckBox createTabButton() {
        if (mContext == null)
            return null;

        CheckBox button = new CheckBox(mContext);
        button.setButtonDrawable(R.color.wl_transparent);
        button.setGravity(Gravity.CENTER);
        button.setBackgroundResource(R.drawable.wl_slt_expand_tab_btn_bg);
        button.setLayoutParams(ViewUtils.WRAP_MATCH);
        button.setMinWidth(TAB_MIN_WIDTH);
        button.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
        return button;
    }

    /**
     * 设置Tab按钮的标题
     * 
     * @param position
     * @param title
     */
    public void setTitle(int position, String title) {
        if (isBtnIndexValid(position) && title != null) {
            CheckBox c = mTabs.get(position);
            // c.setTextColor(mContext.getResources().getColor(R.color.wl_gray));
            c.setText(title);
        }
    }

    /**
     * 设置下拉窗口的视图
     * 
     * @param position
     * @param view
     * @param isFullWidth
     */
    public void setDropView(int position, View view, boolean isFullWidth) {
        if (!isBtnIndexValid(position) || view == null)
            return;
        mDropWinContents.put(position, view);
        PopupWindow pWindow = null;
        if (isFullWidth) {
            pWindow = mPwindow2;
        } else {
            pWindow = mPwindow1;
        }
        mTabs.get(position).setTag(TAG_KEY_DROPWIN, pWindow);

    }

    /**
     * 设置标题样式
     * 
     * @param textSize
     *            标题文字大小，单位是dp
     * @param textColor
     *            标题文字颜色
     * @return 设置成功返回true，否则返回false
     */
    public boolean setTitleStyle(int textSize, int textColor) {
        for (int i = 0; i < mTabs.size(); i++) {
            CheckBox c = mTabs.get(i);
            try {
                c.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
                c.setTextColor(mContext.getResources().getColor(textColor));
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 设置标题样式
     * 
     * @param bg
     *            背景图
     * @param textSize
     * @param textColor
     * @return
     */
    public boolean setTitleStyle(Object bg, int textSize, int textColor) {
        if (bg != null) {
            for (int i = 0; i < mTabs.size(); i++) {
                ViewUtils.setViewBackground(mTabs.get(i), bg);
            }
        }
        return setTitleStyle(textSize, textColor);
    }

    public void setTitleGravity(int gravity) {
        for (int i = 0; i < mTabs.size(); i++) {
            CheckBox c = mTabs.get(i);
            c.setGravity(gravity);
        }
    }

    /**
     * 设置Tab按钮的Padding值
     * 
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    public void setTabPadding(int left, int top, int right, int bottom) {
        paddingLeft = left;
        paddingTop = top;
        paddingRight = right;
        paddingBottom = bottom;
        for (int i = 0; i < mTabs.size(); i++) {
            CheckBox c = mTabs.get(i);
            c.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
        }
    }

    /**
     * 设置图标
     * 
     * @param positionTab
     *            按钮的位置，从0开始
     * @param drawableId
     */
    public void setIcon(int position, int drawableId) {
        Drawable drawable = null;
        try {
            drawable = mContext.getResources().getDrawable(drawableId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (drawable != null) {
            setIcon(position, drawable);
        }
    }

    /**
     * 设置图标
     * 
     * @param position
     *            Tab按钮的位置，从0开始
     * @param drawable
     */
    public void setIcon(int position, Drawable drawable) {
        if (isBtnIndexValid(position) && drawable != null) {
            CheckBox c = mTabs.get(position);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                    drawable.getMinimumHeight());
            c.setCompoundDrawables(drawable, null, null, null);
        }
    }

    public void setRightDrawable(int position, Drawable drawable) {
        if (isBtnIndexValid(position) && drawable != null) {
            CheckBox c = mTabs.get(position);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                    drawable.getMinimumHeight());
            c.setCompoundDrawables(null, null, drawable, null);
            // c.setCompoundDrawablePadding(COMPOUND_D_PADDING);
        }
    }

    public void setRightDrawable(int position, int drawableId) {
        Drawable drawable = null;
        try {
            drawable = mContext.getResources().getDrawable(drawableId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (drawable != null) {
            setRightDrawable(position, drawable);
        }
    }

    public void setDrawablePadding(int position, int pixels) {
        if (isBtnIndexValid(position)) {
            CheckBox c = mTabs.get(position);
            c.setCompoundDrawablePadding(pixels);
        }
    }

    public void setDrawablePadding(int pixels) {
        for (int i = 0; i < mTabs.size(); i++)
            setDrawablePadding(i, pixels);
    }

    /**
     * 判断所给定位置的Button是否存在
     * 
     * @param pos
     * @return
     */
    private boolean isBtnIndexValid(int pos) {
        if (pos > -1 && pos < mTabs.size())
            return true;
        return false;
    }

    /**
     * 获取Tab按钮数
     * 
     * @return
     */
    public int getTabCounts() {
        return mTabs.size();
    }

    /**
     * 隐藏下拉窗口
     * 
     * @return 隐藏成功返回true，否则返回false
     */
    public boolean hideDropdownWindow() {
        boolean b1 = hidePopup(mPwindow1);
        boolean b2 = hidePopup(mPwindow2);
        return b1 || b2;
    }

    /**
     * 判断下拉窗口是否在显示
     * 
     * @return
     */
    public boolean isDropdownWindowShowing() {
        if (mPwindow1 != null && mPwindow1.isShowing())
            return true;
        if (mPwindow2 != null && mPwindow2.isShowing())
            return true;
        return false;
    }

    /**
     * 当下拉窗口消失时，设置上方的Tab按钮为unChecked状态
     */
    @Override
    public void onDismiss() {
        if (checkedButton1 != null) {
            checkedButton1.setChecked(false);
            checkedButton1 = null;
        }

    }

    /**
     * 更新Tab按钮的状态
     * 
     * @param position
     * @param title
     */
    public void onRefresh(int position, String title) {
        setTitle(position, title);
        hideDropdownWindow();
    }
}
